package chapter01.school;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
@SuppressWarnings({"all"})
public class Mytext extends JFrame implements ActionListener {
    //文本域承载编辑的内容，的组件
    JTextArea myTextArea;
    //滚动窗格
    JScrollPane my;
    //按钮
    JButton jButton;
    JLabel statusLabel;

    JCheckBoxMenuItem viewMenu_Status;
    JMenuBar myMenuBar;//上方菜单栏
    JMenu file, edit, source, helpMenu, viewMenu;//菜单栏中选项
    JMenuItem New, Open, Save, NewWindow, exit, SaveAS;//选项中的小选项
    JMenuItem Cut, Copy, Paste, Delete, Time, Brow, Find, Replace, AllSelectd;
    JMenuItem autoLine, autoLine1, FontSet;
    //文本选这框
//    JFileChooser jFileChooser;
    //文件输入流，从中读取数据，打开
    FileReader fileReader;
    //定义一个文件输出流，从中写入数据，保存
    FileWriter fileWriter;
    //定义一个缓冲字符输入流
    BufferedReader bufferedReader;
    //定义一个缓冲字符输出流
    BufferedWriter bufferedWriter;


    public static void main(String[] args) {

        Mytext a = new Mytext();
//        getEnvironmentFont();
    }

    Mytext() {

        myTextArea = new JTextArea();
        my = new JScrollPane(myTextArea);   //标题栏
        myMenuBar = new JMenuBar();
        file = new JMenu("文件");
        edit = new JMenu("编辑");
        source = new JMenu("格式");
        viewMenu = new JMenu("查看");
        viewMenu_Status = new JCheckBoxMenuItem("状态栏");
        helpMenu = new JMenu("帮助");
//        jFileChooser = new JFileChooser();
//        jButton = new JButton("香蕉");
//        jButton.setSize(80, 20);
//        my.add(jButton);
        //设置背景颜色
        myTextArea.setBackground(Color.white);


        New = new JMenuItem("新建");
        New.addActionListener(this);
        New.setActionCommand("create");
        Open = new JMenuItem("打开");


        Open.setActionCommand("open");
        Save = new JMenuItem("保存");

        Save.setActionCommand("save");

        NewWindow = new JMenuItem("新窗口");

        NewWindow.setActionCommand("newwindow");

        SaveAS = new JMenuItem("另存为");

        SaveAS.setActionCommand("SaveAs");

        exit = new JMenuItem("退出");

        exit.setActionCommand("exit");
        Cut = new JMenuItem("剪切");

        Cut.setActionCommand("cut");

        Copy = new JMenuItem("复制");

        Copy.setActionCommand("copy");

        Paste = new JMenuItem("粘贴");

        Paste.setActionCommand("paste");

        Time = new JMenuItem("时间/日期");

        Time.setActionCommand("time");

        Delete = new JMenuItem("删除");

        Delete.setActionCommand("delete");

        Brow = new JMenuItem("使用百度搜索");

        Brow.setActionCommand("brow");

        Find = new JMenuItem("查找");
        Find.addActionListener(this);
        Find.setActionCommand("find");

        Replace = new JMenuItem("替换");

        Replace.setActionCommand("replace");

        AllSelectd = new JMenuItem("全选");

        AllSelectd.setActionCommand("allselectd");

        autoLine = new JMenuItem("自动换行");
        autoLine.addActionListener(this);
        autoLine.setActionCommand("autoLine");

        autoLine1 = new JMenuItem("?自动换行");
        autoLine1.addActionListener(this);
        autoLine1.setActionCommand("autoLine1");

        FontSet = new JMenuItem("字体");
        FontSet.addActionListener(this);
        FontSet.setActionCommand("FontSet");
        myMenuBar.add(file);
        myMenuBar.add(edit);
        myMenuBar.add(source);
        myMenuBar.add(viewMenu);
        myMenuBar.add(helpMenu);

        file.add(New);
        file.addSeparator();
        file.add(Open);
        file.addSeparator();
        file.add(Save);
        file.addSeparator();
        file.add(NewWindow);
        file.addSeparator();
        file.add(SaveAS);
        file.addSeparator();
        file.add(exit);


        edit.add(Cut);
        edit.addSeparator();
        edit.add(Copy);
        edit.addSeparator();
        edit.add(Paste);
        edit.addSeparator();
        edit.add(Delete);
        edit.addSeparator();
        edit.add(Time);
        edit.addSeparator();
        edit.add(Brow);
        edit.addSeparator();
        edit.add(Find);
        edit.addSeparator();
        edit.add(Replace);
        edit.addSeparator();
        edit.add(AllSelectd);

        source.add(autoLine);
        edit.addSeparator();
        source.add(FontSet);
        viewMenu.add(viewMenu_Status);
        this.add(my);
        //设置标题
        this.setTitle("记事本");
        this.setIconImage(new ImageIcon("../image/title.jpg").getImage());
        //将菜单栏添加到我的窗口中 this代表当前对象
        this.setJMenuBar(myMenuBar);
        this.setSize(650, 550);
        this.setLocation(100, 200);
        this.setResizable(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //控制窗口是否可见
        this.setVisible(true);

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("create")) {
            int saveChoose = JOptionPane.showConfirmDialog(this,
                    "您的文件尚未保存，是否保存？", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
            if (saveChoose == JOptionPane.YES_OPTION) {
                JFileChooser jFileChooser = new JFileChooser();
                jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                jFileChooser.setDialogTitle("另存为");
                int result = jFileChooser.showSaveDialog(this);
                if (result == JFileChooser.CANCEL_OPTION) {
                    statusLabel.setText("您没有选择任何文件");
                    return;
                }
                File saveFileName = jFileChooser.getSelectedFile();
                if (saveFileName == null || saveFileName.getName().equals("")) {
                    JOptionPane.showMessageDialog(this, "不合法的文件名", "不合法的文件名",
                            JOptionPane.ERROR_MESSAGE);
                } else {
                    try {
                        fileWriter = new FileWriter(saveFileName);
                        BufferedWriter bfw = new BufferedWriter(fileWriter);
                        bfw.write(myTextArea.getText(), 0, myTextArea.getText().length());
                        bfw.flush();
                        bfw.close();
                        this.setTitle(saveFileName.getName() + " - 记事本");
                    } catch (IOException ioException) {
                    }
                }
            } else if (saveChoose == JOptionPane.NO_OPTION) {
                myTextArea.replaceRange("", 0, myTextArea.getText().length());
                this.setTitle("无标题 - 记事本");
            } else if (saveChoose == JOptionPane.CANCEL_OPTION) {
                return;
            }

        }else if(e.getActionCommand().equals("find")){
            find();
        }else if(e.getActionCommand().equals("autoLine")){
            myTextArea.setLineWrap(true);
            source.remove(autoLine);
            source.add(autoLine1,0);
        }else if(e.getActionCommand().equals("autoLine1")){
            myTextArea.setLineWrap(true);
            source.remove(autoLine1);
            source.add(autoLine,0);
        }else if(e.getSource() == FontSet){
//            final  JDialog dialog = new JDialog(this,"字体",true);
//            JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
//            panel.add(new JLabel("字体"));
//            final JComboBox cmb = new JComboBox();
//            //创建JComboBox
//            java.util.List<String> list = FontTool.getLocalFontFamily();
//            for (String cc :
//                    list) {
//                cmb.addItem(cc);
//            }
            myTextArea.requestFocus();
            font();
        }

    }
        public void font() {
            final JDialog fontDialog = new JDialog(this, "字体设置", false);
            Container con = fontDialog.getContentPane();
            con.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel fontLabel = new JLabel("字体(F)：");
            fontLabel.setPreferredSize(new Dimension(100, 20));// 构造一个Dimension，并将其初始化为指定宽度和高度
            JLabel styleLabel = new JLabel("字形(Y)：");
            styleLabel.setPreferredSize(new Dimension(100, 20));
            JLabel sizeLabel = new JLabel("大小(S)：");
            sizeLabel.setPreferredSize(new Dimension(100, 20));
            final JLabel sample = new JLabel("李童的记事本-TongLee's Notepad");
            // sample.setHorizontalAlignment(SwingConstants.CENTER);
            final JTextField fontText = new JTextField(9);
            fontText.setPreferredSize(new Dimension(200, 20));
            final JTextField styleText = new JTextField(8);
            styleText.setPreferredSize(new Dimension(200, 20));
            final int style[] = { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD + Font.ITALIC };
            final JTextField sizeText = new JTextField(5);
            sizeText.setPreferredSize(new Dimension(200, 20));
            JButton okButton = new JButton("确定");
            JButton cancel = new JButton("取消");
            cancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    fontDialog.dispose();
                }
            });
            Font currentFont = myTextArea.getFont();
            fontText.setText(currentFont.getFontName());
            fontText.selectAll();
            // styleText.setText(currentFont.getStyle());
            // styleText.selectAll();
            if (currentFont.getStyle() == Font.PLAIN)
                styleText.setText("常规");
            else if (currentFont.getStyle() == Font.BOLD)
                styleText.setText("粗体");
            else if (currentFont.getStyle() == Font.ITALIC)
                styleText.setText("斜体");
            else if (currentFont.getStyle() == (Font.BOLD + Font.ITALIC))
                styleText.setText("粗斜体");
            styleText.selectAll();
            String str = String.valueOf(currentFont.getSize());
            sizeText.setText(str);
            sizeText.selectAll();
            final JList fontList, styleList, sizeList;
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            final String fontName[] = ge.getAvailableFontFamilyNames();
            fontList = new JList(fontName);
            fontList.setFixedCellWidth(86);
            fontList.setFixedCellHeight(20);
            fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            final String fontStyle[] = { "常规", "粗体", "斜体", "粗斜体" };
            styleList = new JList(fontStyle);
            styleList.setFixedCellWidth(86);
            styleList.setFixedCellHeight(20);
            styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            if (currentFont.getStyle() == Font.PLAIN)
                styleList.setSelectedIndex(0);
            else if (currentFont.getStyle() == Font.BOLD)
                styleList.setSelectedIndex(1);
            else if (currentFont.getStyle() == Font.ITALIC)
                styleList.setSelectedIndex(2);
            else if (currentFont.getStyle() == (Font.BOLD + Font.ITALIC))
                styleList.setSelectedIndex(3);
            final String fontSize[] = { "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36",
                    "48", "72" };
            sizeList = new JList(fontSize);
            sizeList.setFixedCellWidth(43);
            sizeList.setFixedCellHeight(20);
            sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            fontList.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent event) {
                    fontText.setText(fontName[fontList.getSelectedIndex()]);
                    fontText.selectAll();
                    Font sampleFont1 = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
                            Integer.parseInt(sizeText.getText()));
                    sample.setFont(sampleFont1);
                }
            });
            styleList.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent event) {
                    int s = style[styleList.getSelectedIndex()];
                    styleText.setText(fontStyle[s]);
                    styleText.selectAll();
                    Font sampleFont2 = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
                            Integer.parseInt(sizeText.getText()));
                    sample.setFont(sampleFont2);
                }
            });
            sizeList.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent event) {
                    sizeText.setText(fontSize[sizeList.getSelectedIndex()]);
                    // sizeText.requestFocus();
                    sizeText.selectAll();
                    Font sampleFont3 = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
                            Integer.parseInt(sizeText.getText()));
                    sample.setFont(sampleFont3);
                }
            });
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Font okFont = new Font(fontText.getText(), style[styleList.getSelectedIndex()],
                            Integer.parseInt(sizeText.getText()));
                    myTextArea.setFont(okFont);
                    fontDialog.dispose();
                }
            });
            JPanel samplePanel = new JPanel();
            samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));
            // samplePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
            samplePanel.add(sample);
            JPanel panel1 = new JPanel();
            JPanel panel2 = new JPanel();
            JPanel panel3 = new JPanel();

            panel2.add(fontText);
            panel2.add(styleText);
            panel2.add(sizeText);
            panel2.add(okButton);
            panel3.add(new JScrollPane(fontList));// JList不支持直接滚动，所以要让JList作为JScrollPane的视口视图
            panel3.add(new JScrollPane(styleList));
            panel3.add(new JScrollPane(sizeList));
            panel3.add(cancel);
            con.add(panel1);
            con.add(panel2);
            con.add(panel3);
            con.add(samplePanel);
            fontDialog.setSize(350, 340);
            fontDialog.setLocation(200, 200);
            fontDialog.setResizable(false);
            fontDialog.setVisible(true);
        }
    public void find(){
        final JDialog findDialog = new JDialog(this, "查找", false);//false时允许其他窗口同时处于激活状态(即无模式)
        Container con = findDialog.getContentPane();//返回此对话框的contentPane对象
        con.setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel findContentLabel = new JLabel("查找内容(N)：");
        final JTextField findText = new JTextField(15);
        JButton findNextButton = new JButton("查找下一个(F)：");
        final JCheckBox matchCheckBox = new JCheckBox("区分大小写(C)");
        ButtonGroup bGroup = new ButtonGroup();
        final JRadioButton upButton = new JRadioButton("向上(U)");
        final JRadioButton downButton = new JRadioButton("向下(U)");
        downButton.setSelected(true);//默认选择向下搜索
        bGroup.add(upButton);
        bGroup.add(downButton);
        /*ButtonGroup此类用于为一组按钮创建一个多斥（multiple-exclusion）作用域。
        使用相同的 ButtonGroup 对象创建一组按钮意味着“开启”其中一个按钮时，将关闭组中的其他所有按钮。*/
        /*JRadioButton此类实现一个单选按钮，此按钮项可被选择或取消选择，并可为用户显示其状态。
        与 ButtonGroup 对象配合使用可创建一组按钮，一次只能选择其中的一个按钮。
        （创建一个 ButtonGroup 对象并用其 add 方法将 JRadioButton 对象包含在此组中。）*/
        JButton cancel = new JButton("取消");

        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        JPanel panel3 = new JPanel();
        JPanel directionPanel = new JPanel();
        directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));
        //设置directionPanel组件的边框;
        //BorderFactory.createTitledBorder(String title)创建一个新标题边框，使用默认边框（浮雕化）、默认文本位置（位于顶线上）、默认调整 (leading) 以及由当前外观确定的默认字体和文本颜色，并指定了标题文本。
        directionPanel.add(upButton);
        directionPanel.add(downButton);
        panel1.setLayout(new GridLayout(2, 1));
        panel1.add(findNextButton);
        panel1.add(cancel);
        panel2.add(findContentLabel);
        panel2.add(findText);
        panel2.add(panel1);
        panel3.add(matchCheckBox);
        panel3.add(directionPanel);
        con.add(panel2);
        con.add(panel3);
        findDialog.setSize(410, 180);
        findDialog.setResizable(false);//不可调整大小
        findDialog.setLocation(230, 280);
        findDialog.setVisible(true);
        //查找下一个的监视器:
        findNextButton.addActionListener((e)->{
//            String strA;
//            strA = myTextArea.getText();
            int k = 1;
            myTextArea.setCaretPosition(k);
            myTextArea.select(k,k + 2);
            System.out.println(myTextArea.getCaretPosition());
        });
        cancel.addActionListener((e -> {
            System.out.println(myTextArea.getCaretPosition());
        }));
    }
    public static void getEnvironmentFont(){
    GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = e.getAvailableFontFamilyNames();
    for (String fontName : fontNames) {
        System.out.println(fontName);
    }
    }
    public static void getEnvironmentFontArrays() {
        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Font[] fonts = e.getAllFonts();
        for (Font font : fonts) {
            String fontName = font.getFontName();
            System.out.println(fontName);
        }
    }


}
//class FontTool{
//    public static java.util.List<String> getLocalFontFamily(){
//        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
//        Font[] fonts = e.getAllFonts();
//        java.util.List<String> strings = new ArrayList<>();
//        for (Font font : fonts) {
//            strings.add(font);
//        }
//    }
//}

